#include <stdio.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <netdb.h>

static void
error(char *msg)
{
    fputs(strerror(errno), stderr);
    fputs(": ", stderr);
    fputs(msg, stderr);
    fputc('\n', stderr);
    exit(1);
}

int main(int argc, char **argv)
{
    int z;
    int s;
    char *srvr_addr = NULL;
    struct sockaddr_in adr_srvr;
    size_t len_srvr;

    struct servent *sp;
    char dtbuff[128];

    // get server address  from the argument
    if ( argc >= 2 )
	srvr_addr = argv[1];
    else {
	fprintf(stderr, "Provide server address\n");
    	exit(1);
    }

    // set service structure for daytime service
    sp = getservbyname("daytime", "tcp");
    if ( ! sp ) {
	fprintf(stderr, "Unknown service: daytimetcv\n");
	exit(1);
    }

    // initialize socket address
    memset(&adr_srvr, 0, sizeof(adr_srvr));
    adr_srvr.sin_family = AF_INET;
    adr_srvr.sin_port = sp->s_port;
    if ( inet_aton(srvr_addr, &adr_srvr.sin_addr) == -1 )
	error("inet_aton()");

    len_srvr = sizeof(adr_srvr);

    // set socket address with fd
    s = socket(AF_INET, SOCK_STREAM, 0);
    if ( s == -1 )
	error("socket()");

    // connect socket to the server
    z = connect(s, &adr_srvr, len_srvr);
    if ( z == -1 )
	error("connect()");

    // read data from the server
    z = read(s, &dtbuff, sizeof(dtbuff));
    if ( z == -1 )
	error("read()");

    dtbuff[z] = 0;

    printf("Date and time is: %s\n", dtbuff);

    //close socket
    close(s);

    return 0;
}
